<?php
namespace App\Http\Controllers\Api\Tg;

use DB;

use Carbon\Carbon;

use App\Models\Tg\Tg;  //团购维护主表

use App\Models\ConfigureFunction; //功能配置表

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Redis as Redis;

use App\Models\Mall\MallMaster;

use App\Models\Pay\SysPaytype;

use App\Models\Pay\SysOnlineParameter;

use App\Service\WdhService;

use App\Service\Order\TgOrderService;

use App\Models\Bill\Bill;

use App\Models\Bill\BillGoods;

use App\Service\Pay\WxPayService;

class TgBillSubmitController extends Controller
{

    /**
     * 提交订单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function billSubmit(Request $request)
    {

        $session_id = $request->input('session_id', session_id());
        $platform = $request->input('platform', 6);
        $mobile = $request->input('mobile');
        $name = $request->input('name');
        $payPwd = $request->input('payPwd');
        $sendId = $request->input('sendId'); //配送时间ID
        $timeID = $request->input('timeID'); //配送时间段ID
        $datetime = Carbon::now();

        if (empty($session_id)) {
            return response()->json(['code' => 100001, 'message' => '缺少参数：session_id']);
        }

        $pcustID = get_customer_id($session_id, $platform);
        if (!$pcustID) {
            return response()->json(['code' => 100002, 'message' => '请登录']);
        }

        /**
         * ===================================
         * 获取团购购物车数据
         * ===================================
         */
        $tuan_cart_data = json_decode(Redis::get('TUAN_BILL_DATA_' . $pcustID), true);
        if (!$tuan_cart_data) {
            return response()->json(['code' => 100003, 'message' => '暂无团购订单信息']);
        }

        if (!isset($tuan_cart_data['sendTypeID']) || !in_array($tuan_cart_data['sendTypeID'], [1, 2])) {
            return response()->json(['code' => 100003, 'message' => '请选择配送方式']);
        }

        if (!isset($tuan_cart_data['deliverid']) || !ebsig_is_int($tuan_cart_data['deliverid'])) {
            return response()->json(['code' => 100005, 'message' => '请选择收货地址']);
        }

        $id = $tuan_cart_data['tuan_id']; //团购ID
        $goods_amount = $tuan_cart_data['goods'][0]['goods_amount']; //商品数量
        $postID = $tuan_cart_data['goods'][0]['postID']; //商品ID
        $sendTypeID = $tuan_cart_data['sendTypeID']; //配送方式id

        /**
         * ============================
         * 检查团购信息
         * ==============================
         */
        $tuan_data = Tg::getCache($id);
        if ( !$tuan_data || $tuan_data['useFlg'] == 0) {
            return response()->json(['code' => 100004, 'message' => '团购已结束']);
        }

        if ( $tuan_data['start_time'] > $datetime ){
            return response()->json(['code' => 100005, 'message' => '团购活动未开始']);
        }
        if ( $tuan_data['end_time'] < $datetime ) {
            return response()->json(['code' => 100006, 'message' => '团购活动已结束']);
        }

        //获取加入购物车的团购商品数据
        $tuang_goods = [];
        if ( $tuan_data['goods'] ) {
            foreach( $tuan_data['goods'] as $item ){
                if( $postID == $item['postID'] ){
                    $tuang_goods = $item;
                    break;
                }
            }
            if( empty($tuang_goods) ){
                return response()->json(['code' => 100007, 'message' => '团购商品不存在']);
            }
        }

        //判断是否已参与过该团
        if ($tuan_cart_data['parent_bill_no']) {
            $customer_tg = Redis::get('G_WDH_CUSTOMER_TG_' . $id . '_'  . $pcustID);
            if( !empty( $customer_tg )){
                return response()->json(['code' => 100008, 'message' => '您已参与过该团了']);
            }
        }

        //判断会员限购数
        if ( $tuan_data['user_can_buy_num'] > 0 ) {

            //查询会员订单信息
            $customer_tg_bill = Bill::select('bill_no')->where([
                ['pcustID', $pcustID],
                ['activity_id', $id],
                ['billType', 9],
                ['bill_status', '<>', 5],
            ])->get()->toArray();
            if ($customer_tg_bill) {
                $customer_buy_amount = 0; //会员已购买数量
                foreach ($customer_tg_bill as &$bill) {
                    $customer_buy_amount += BillGoods::where('bill_no', $bill['bill_no'])->sum('goods_amount');
                }
                if ( $tuan_data['user_can_buy_num'] < $customer_buy_amount + $goods_amount ) {
                    return response()->json(['code' => 100009, 'message' => '超出商品限购数量']);
                }
            }

        }

        //判断开团订单还是参团订单
        if ( $tuan_cart_data['parent_bill_no'] ) {

            //判断主订单号是否存在
            $parent_bill = Bill::find($tuan_cart_data['parent_bill_no']);
            if ( !$parent_bill ) {
                return response()->json(['code' => 100010, 'message' => '主团购单信息不存在']);
            }
            if ( $parent_bill->pay_status == 0 || $parent_bill->pay_status == 2 ) {
                return response()->json(['code' => 100010, 'message' => '主团购单未支付']);
            }
            if ( $parent_bill->bill_status == 1 ) {
                return response()->json(['code' => 100010, 'message' => '主团购单已组团成功']);
            }
            if ( $parent_bill->bill_status == 5 ) {
                return response()->json(['code' => 100010, 'message' => '主团购单已取消']);
            }

        }

        $pickup_start_time = null;
        $pickup_end_time = null;
        $send_time = null;

        //送货上门
        if ($sendTypeID == 1) {
            $tuan_cart_data['ziti'] = 0;
            $tuan_cart_data['sendTypeName'] = '送货上门';

            //查询配送时间信息
            $send_config = ConfigureFunction::getConfigure(12);
            if (!$send_config || !$send_config['detail']) {
                $pickup_start_time = date('Y-m-d H:i:s');
                $pickup_end_time = date('Y-m-d H:i:s',strtotime('+365 day'));
            }

            $send_time_type = $send_config['send_time_type'];
            $send_time = '';
            if ($send_config['detail']) {
                $date = date('Y-m-d', strtotime('+'.$sendId.' days'));
                foreach($send_config['detail'] as &$time){
                    if ($time['timeID'] == $timeID) {
                        if ($send_time_type == 1) {
                            $send_time = $time['timeName'];
                            break;
                        }

                        if ($send_time_type == 2) {
                            $pickup_start_time = $date . ' ' . $time['send_start_time'];
                            $pickup_end_time = $date . ' ' . $time['send_end_time'];
                            break;
                        }

                    }
                }
            }
        }

        //门店自提
        if ($sendTypeID == 2) {
            if (empty($mobile)) {
                return response()->json(['code' => 1000011, 'message' => '请输入提货人手机']);
            } else if (!isMobile($mobile)) {
                return response()->json(['code' => 1000011, 'message' => '提货人手机号码格式错误']);
            }

            if (empty($name)) {
                return response()->json(['code' => 1000011, 'message' => '请输入提货人姓名']);
            }

            //查询自提时间信息
            $ziti_config = ConfigureFunction::getConfigure(13);
            if (!$ziti_config || !$ziti_config['detail']) {
                $pickup_start_time = date('Y-m-d H:i:s');
                $pickup_end_time = date('Y-m-d H:i:s',strtotime('+365 day'));
            }

            if ($ziti_config['detail']) {
                $date = date('Y-m-d', strtotime('+'.$sendId.' days'));
                foreach($ziti_config['detail'] as &$time){
                    if ($time['timeID'] == $timeID) {
                        $pickup_start_time = $date . ' ' . $time['send_start_time'];
                        $pickup_end_time = $date . ' ' . $time['send_end_time'];
                        break;
                    }
                }
            }

            $tuan_cart_data['deliver_mobile'] = $mobile;
            $tuan_cart_data['deliver_name'] = $name;
            $tuan_cart_data['ziti'] = 1;
            $tuan_cart_data['sendTypeName'] = '门店自提';
        }

        //获取openId
        $openId = '';
        $customer_redis = json_decode(app('redis')->get('WX_APPLET_USER_' . $session_id), true);
        if (isset($customer_redis['openId']) && !empty($customer_redis['openId'])) {
            $openId = $customer_redis['openId'];
        }

        $tuan_cart_data['openId'] = $openId;
        $tuan_cart_data['pcustID'] = $pcustID;
        $tuan_cart_data['send_time'] = $send_time;
        $tuan_cart_data['pickup_start_time'] = $pickup_start_time;
        $tuan_cart_data['pickup_end_time'] = $pickup_end_time;
        $tuan_cart_data['activity_id'] = $id; //团购ID
        $tuan_cart_data['invoice'] = 0;
        $tuan_cart_data['supplier_id'] = 1;;
        $tuan_cart_data['payTypeID'] = 50;
        $tuan_cart_data['payTypeName'] = '微信支付';
        $tuan_cart_data['pay_type'] = 2;
        $tuan_cart_data['payPwd'] = $payPwd;
        $tuan_cart_data['billPlatform'] = 1; //订单平台
        $tuan_cart_data['billChannel'] = 15;//订单渠道
        $tuan_cart_data['billType'] = 9;
        $tuan_cart_data['tuan_store'] = $tuang_goods['tuan_store']; //团购库存
        $tuan_cart_data['tuan_type'] = $tuan_data['tuan_type']; //团购类型
        $tuan_cart_data['bill_tariff_money'] = 0;

        //订单支付信息
        $tuan_cart_data['pay'][] = [
            'payTypeID' => 50,
            'payTypeName' => '微信支付',
            'type' => 2,
            'pay_amount' => $tuan_cart_data['bill_payable'] > 0 ? $tuan_cart_data['bill_payable'] : 0.00,
            'deduct_amount' => 0.00,
            'pay_time' => null
        ];

        //余额使用
        if (isset($tuan_cart_data['use_balance']) && !empty($tuan_cart_data['use_balance'])) {
            $tuan_cart_data['pay'][] = array(
                'payTypeID' => 2,
                'payTypeName' => '余额',
                'type' => 4,
                'pay_amount' => $tuan_cart_data['use_balance']['deduct_amount'],
                'deduct_amount' => $tuan_cart_data['use_balance']['deduct_amount'],
                'pay_time' => $tuan_cart_data['use_balance']['deduct_amount'] == 0 ? $datetime : null
            );
        }


        //积分使用
        if (isset($tuan_cart_data['use_points']) && !empty($tuan_cart_data['use_points'])) {
            $tuan_cart_data['pay'][] = array(
                'payTypeID' => 3,
                'payTypeName' => '积分',
                'type' => 5,
                'pay_amount' => $tuan_cart_data['use_points']['points'],
                'deduct_amount' => $tuan_cart_data['use_points']['points'],
                'pay_time' => $tuan_cart_data['use_points']['points'] == 0 ? $datetime : null
            );
        }

        //实例化团购订单类
        $tg_order_service = new TgOrderService($tuan_cart_data);

        //新增订单
        $res = $tg_order_service->submit();
        if ( $res['code'] != 200 ) {
            return response()->json(['code' => $res['code'], 'message' => $res['message']]);
        }

        //订单新增成功移除购物车数据
        Redis::del('TUAN_BILL_DATA_' . $pcustID);

        $bill_no = $res['data']['bill_no'];
        $parent_bill_no = $res['data']['parent_bill_no'];
        $pay_amount = $res['data']['pay_amount'];
        $mallID = $res['data']['mallID'];
        $pay_status = $res['data']['pay_status'];

        $return_data = array(
            'bill_no' => $bill_no,
            'parent_bill_no' => $parent_bill_no,
            'payTypeID' => 50,
            'pay_status' => $pay_status,
            'pay' => []
        );

        if( $pay_status == 1 ){
            return response()->json(['code' => 200, 'message' => 'ok', 'data' => $return_data]);
        }

        $trade_type = '';
        $wx_config_seeting = ConfigureFunction::getConfigureField(41,'wechat_type');
        if ( $wx_config_seeting == 1) {
            $trade_type = 'JSAPI';
        }
        if ( $wx_config_seeting != 1 ) {
            $trade_type = 'NATIVE';
        }

        //微信异步接收路径
        $notify_url = $request->getSchemeAndHttpHost() . '/onlinepay/weixin/notify';

        $params = [
            'out_trade_no' => $bill_no,
            'trade_type' => $trade_type,
            'payTypeID' => 50,
            'mallID' => $mallID,
            'body' => '微商城',
            'total_fee' => $pay_amount,
            'pcustID' => $pcustID,
            'type' => 4,
            'openId' => $res['data']['openId'],
            'notify_url' => $notify_url
        ];

        $WxPayService = new WxPayService($params);

        $wx_pay = $WxPayService->request();
        if ($wx_pay['code'] == 200) {
            $return_data['pay'] = $wx_pay['data'];
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $return_data]);

    }


    /**
     * 检查支付
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function checkPay(Request $request){

        $req_data = $request->all();

        if ( !isset($req_data['id']) || empty($req_data['id']) ) {
            return response()->json(['code' => 400, 'message' => '参数错误']);
        }

        if (!isset($req_data['session_id']) || empty($req_data['session_id'])) {
            return response()->json(['code' => 400, 'message' => '参数错误']);
        }

        $cust_info = Redis::get('WX_APPLET_USER_' . $req_data['session_id']);
        if ($cust_info) {
            $cust_info =  json_decode($cust_info, true);
        }
        $pcustID = $cust_info['pcustID'];
        if (!$pcustID) {
            return response()->json(['code' => 400, 'message' => '请登录']);
        }

        $bill_no = $req_data['id'];

        //查询订单信息
        $tuan_bill_data = Bill::where(['bill_no' => $bill_no])->first();
        if ( !$tuan_bill_data ) {
            return response()->json(['code' => 400, 'message' => '订单信息不存在']);
        }
        $tuan_bill_data = $tuan_bill_data->toArray();

        if ( $tuan_bill_data['bill_status'] == 1 || $tuan_bill_data['pay_status'] == 1 ) {
            return response()->json(['code' => 400, 'message' => '订单已支付']);
        }

        //查询团购信息
        $tuanData = Tg::getCache($tuan_bill_data['activity_id']);
        if (!$tuanData || $tuanData['useFlg'] != 1) {
            return response()->json(['code' => 400, 'message' => '该团购已不在地球上']);
        }

        //判断是否是主订单
        if ( $bill_no != $tuan_bill_data['parent_bill_no'] ) {
            $parent_bill_data = Bill::where(['bill_no' => $tuan_bill_data['parent_bill_no']])->first();
            if ( !$parent_bill_data ) {
                return response()->json(['code' => 400, 'message' => '订单信息不存在']);
            }
            $parent_bill_data = $parent_bill_data->toArray();

            if ( $parent_bill_data['pay_status'] == 0 ) {
                return response()->json(['code' => 400, 'message' => '主团购单未支付']);
            }

            if ( $parent_bill_data['bill_status'] == 1 ) {
                return response()->json(['code' => 400, 'message' => '主团购单已组团成功']);
            }

            if ( $parent_bill_data['bill_status'] == 5 ) {
                return response()->json(['code' => 400, 'message' => '主团购单已在有效时间内，未达成最小成团数，拼团失败']);
            }

        }

        if ( !isset($req_data['payTypeID']) || !ebsig_is_int($req_data['payTypeID']) ) {
            $payTypeID = $tuan_bill_data['payTypeID'];
        } else {
            $payTypeID = $req_data['payTypeID'];
        }

        //返回的数据
        $return_array = array(
            'payTypeID' => $payTypeID,
            'bill_payable' => $tuan_bill_data['bill_payable'],
            'online_pay' => array(),
            'pay_data' => array(
                'code' => 200
            )
        );

        $bill_config = $tuanData['config'];

        //支付配置文件
        $is_open_mall_area_pay = ConfigureFunction::getConfigureField(9, 'is_open_mall_area_pay');

        //是否开启选店
        $is_open_choose_mall = ConfigureFunction::getConfigureField(8, 'is_open_choose_mall');

        $pay_area_id = 1;

        //是否开启门店多区域支付
        if ( $is_open_mall_area_pay == 1 && $is_open_choose_mall == 1 ) {
            if (!isset($req_data['mallID']) || !ebsig_is_int($req_data['mallID'])) {
                return response()->json(['code' => 400, 'message' => '未选店']);
            }

            //查询门店信息
            $cust_mall_data = MallMaster::where(['mallID' => $req_data['mallID']])->first();
            if (!$cust_mall_data) {
                return response()->json(['code' => 400, 'message' => '门店信息不存在']);
            }
            $cust_mall_data = $cust_mall_data->toArray();

            $pay_area_id = $cust_mall_data['mallareaID'];
        }

        //查询在线支付方式列表
        $online_data = SysPaytype::where([ 'type' => 2 , 'useFlg' => 1 ])->get()->toArray();
        if ( !$online_data ) {
            return response()->json(['code' => 400, 'message' => '支付方式没有找到']);
        }

        //选中的在线支付参数数组
        $online_parameter_data = array();

        foreach($online_data as $online){

            if (!in_array($online['payTypeID'], explode(',', $bill_config['pay_type']))){
                continue;
            }

            if ($online['payTypeID'] != 5) {
                continue;
            }

            //查询支付方式参数信息
            $online_parameter_array = SysOnlineParameter::where(['payTypeID' => $online['payTypeID'], 'area_id' => $pay_area_id])->first();
            if ( !$online_parameter_array ) {
                continue;
            }
            $online_parameter_array = $online_parameter_array->toArray();

            if ( empty($online_parameter_data) || $online['payTypeID'] == $payTypeID ) {
                $online_parameter_data = $online_parameter_array;
            }
            $return_array['online_pay'][$online['payTypeID']] = array(
                'payTypeID' => $online['payTypeID'],
                'payTypeName' => $online['payTypeName'],
                'alias' => $online_parameter_array['alias'],
                'payment_platform' => $online['payment_platform'],
                'memo' => $online['memo'],
                'logo_img' => $online['logo_img'],
                'selected' => 0
            );

        }

        if ( empty($online_parameter_data) ) {
            return response()->json(['code' => 400, 'message' => '支付参数没有找到']);
        }
        $return_array['online_pay'][$online_parameter_data['payTypeID']]['selected'] = 1;

        $online_parameter_data['bill_no'] = $tuan_bill_data['bill_no'];
        $online_parameter_data['pcustID'] = $tuan_bill_data['pcustID'];
        $online_parameter_data['pay_amount'] = $tuan_bill_data['bill_payable'];
        $online_parameter_data['mallID'] = $tuan_bill_data['mallID'];
        $online_parameter_data['mallCode'] = $tuan_bill_data['mallCode'];
        $online_parameter_data['channelType'] = '08';//银联渠道类型

        //获取在线支付信息
        $send_data = array(
            'data' => $online_parameter_data,
            'type' => 4
        );
        $pay_data = WdhService::onlinePaySend($send_data);

        $return_array['pay_data'] = $pay_data['data'];
        
        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $return_array]);
    }

}